package com.minivision.fdiot.mqtt;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.minivision.fdiot.protopool.MqttOpException;
import com.minivision.fdiot.protopool.Packet.Head.Type;

import lombok.extern.slf4j.Slf4j;

/**
 * MQTT消息容器
 * @author hughzhao
 * @2018年3月2日
 */
@Component
@Slf4j
public class MessageContext {
  
  @Value("${mqtt.response.timeout:10}")
  private long responseTimeoutInSeconds = 10;

  private ConcurrentMap<Long, RequestFuture<?>> reqCache = new ConcurrentHashMap<>();
  
  private long timeout;
  
  @PostConstruct
  private void init() {
    timeout = TimeUnit.SECONDS.toNanos(responseTimeoutInSeconds);
  }
  
  /**
   * 定时任务检查容器中的超时请求
   */
  @Scheduled(fixedRate = 5000)
  public void checkExpire() {
    long start = System.nanoTime();
    for (Entry<Long, RequestFuture<?>> entry : reqCache.entrySet()) {
        RequestFuture<?> req = entry.getValue();
        long aliveTime = System.nanoTime() - req.getBuildNanoTime();
        if (req != null && aliveTime > timeout) {
            req = reqCache.remove(entry.getKey());
            // check again in case of anyone else removed it
            if (req != null) {
                req.fail(new MqttOpException(Type.RESPONSE_TIMEOUT, "Request timeout"));
                log.warn("request {} timeout after {}ns", req.getRequest(), aliveTime);
            }
        }
    }
    long duration = System.nanoTime() - start;
    log.trace("MQTT TimeoutChecker finished in {}ns", duration);
  }
  
  public void add(RequestFuture<?> req) {
      long id = req.getRequest().getHead().getId();
      if (reqCache.putIfAbsent(id, req) != null) {
          throw new IllegalArgumentException("Request with same id " + req.getRequest().getHead().getId()
                  + " already exists");
      }
  }

  public RequestFuture<?> remove(long id) {
      return reqCache.remove(id);
  }
  
}
